<script setup lang="ts">
import {nextTick, onBeforeUnmount, ref} from 'vue'
import { LuckyWheel } from '@lucky-canvas/vue'
import { VaButton } from 'vuestic-ui'
import { useDrawPage } from "./composables/useDrawPage";

const { dataList, isLoading, sorting, pagination, filters, fetch, activeDraw } = useDrawPage()

const endCallback = (prize: string) => {
  console.log('endCallback', prize)
}
const myLucky = ref(null);
const refreshTimer = ref(null) // 定时器 ID


const prizes = ref([])

dataList.value.forEach(item => {
  prizes.value.push({
    background: '#e9e8fe',
    imgs: [
      {
        text: item.nickname,
        src: item.headimgurl
      }
    ]
  })
})

const onActiveDraw = async ()  =>{
    await activeDraw();
}

const onStart = () => {
  console.log('开始转盘了')
}

const onEnd = (prize) => {
  console.log('转盘结束，抽到：', prize.imgs[0].text)
}

const blocks = [{ padding: '13px', background: '#617df2' }];
const defaultConfig = {
  speed: 3,
}
const buttons = [{
  radius: '35%',
  background: '#8a9bf3',
  pointer: true,
  fonts: [{ text: '一等奖', top: '-10px' }]
}]

const handleClick = () => {

  onActiveDraw()

  // 模拟点击，转到某一个奖品（比如随机）
  const index = Math.floor(Math.random() * prizes.length)

  refreshTimer.value = setInterval(async () => {
    console.log('刷新奖品...')

    await loadPrizes()

    await nextTick()

  }, 2000)

  myLucky.value.play();
  setTimeout(() => {
    // 停止刷新
    clearInterval(refreshTimer.value)
    myLucky.value.stop(index)
  }, 10000)
}

const loadPrizes = async () => {
  filters.value.pageNumber = 1 + filters.value.pageNumber;
  await fetch()
  if (dataList.value.length < 5) {
    filters.value.pageNumber = 0;
  } else {
    prizes.value = [];
    dataList.value.forEach(item => {
      prizes.value.push({
        background: '#e9e8fe',
        imgs: [
          {
            text: item.nickname,
            src: item.headimgurl
          }
        ]
      })
    })
  }

}

onBeforeUnmount(() => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
  }
})

</script>

<template>
  <div class="flex flex-col md:flex-row gap-2 mb-2 justify-between">
    <div class="flex flex-col md:flex-row gap-2 justify-start">
      <VaInput v-model="filters.activityId" placeholder="Search">
        <template #prependInner>
          <VaIcon name="search" color="secondary" size="small" />
        </template>
      </VaInput>
      <VaInput v-model="filters.prizeId" placeholder="Search">
        <template #prependInner>
          <VaIcon name="search" color="secondary" size="small" />
        </template>
      </VaInput>
    </div>
  </div>

  <div class="p-4">
    <LuckyWheel
      ref="myLucky"
      width="600px"
      height="600px"
      :prizes="prizes"
      :blocks="blocks"
      :buttons="buttons"
      :defaultConfig="defaultConfig"
      @start="onStart"
      @end="onEnd"
    />
    <VaButton class="mt-4" @click="handleClick">开始抽奖</VaButton>
  </div>
</template>

<style scoped lang="scss">

</style>
